<?php

namespace App\Http\Controllers\api;

use App\ActivityBargain;
use App\ActivityBargainInitiate;
use App\ActivityBargainJoin;
use App\ActivityGroup;
use App\ActivityGroupAdd;
use App\ActivityGroupPrice;
use App\ActivityGroupRefund;
use App\Exceptions\OrderException;
use App\Files;
use App\Goods;
use App\GoodsBanner;
use App\GoodsImg;
use App\GoodSpu;
use App\GoodsSnapshot;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\OrderItem;
use App\Orders;
use App\User;
use App\UserDaka;
use App\UserInfo;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener;

class ActivityController extends Controller
{
    public function fiberRecord(Request $request){
        $phone    = $request->get('phone');
        $fiberNum = !is_null($request->get('fiber_num')) ? $request->get('fiber_num') : 0.0;

        /** @var User $thisUser */
        $thisUser = User::wherePhone($phone)->first();
        if(!$thisUser)
            return response()->json(['level' => 'error','message' => '该手机号未绑定用户']);

        //获取今日开始时间和结束时间
        $ty = date('Y',time());
        $tm = date('m',time());
        $td = date('d',time());
        $todayStartTime = mktime(0,0,0,$tm,$td,$ty);
        $todayEndTime   = mktime(23,59,59,$tm,$td,$ty);

        /** @var UserDaka $userDaka */
        $userDaka = UserDaka::whereUserId($thisUser->id)->whereBetween('daka_time',[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->first();
        if(!$userDaka){
            $userDaka = new UserDaka();
            $userDaka->user_id             = $thisUser->id;
            $userDaka->daka_time           = date('Y-m-d H:i:s',time());
            $userDaka->fiber_num           = $fiberNum;
            $userDaka->save();
        }else{
            $userDaka->fiber_num = $fiberNum;
            $userDaka->save();
        }

        return response()->json(['level' => 'success','message' => '记录成功','data' => $userDaka]);
    }

    /**
     * 获取砍价活动列表
     * @author 张寅虎
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivityBargainList(Request $request){

        /** @var ActivityBargain $activityBargain */
        $activityBargainList = ActivityBargain::whereStatus(1)->orderBy('created_at','desc')->get();
        if(count($activityBargainList) > 0){
            foreach($activityBargainList as $activityBargain){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereType('bargain')->whereIsShop(1)->whereId($activityBargain->goods_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);

                    $activityBargain->goods_info = $thisGoods;
                }else{
                    $activityBargain->goods_info = null;
                }


            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityBargainList]);
    }

    /**
     * 获取砍价详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivityBargainDetail(Request $request){
        $activityBargainId = !is_null($request->get('activity_bargain_id')) ? $request->get('activity_bargain_id') : 0;

        /** @var ActivityBargain $thisActivityBargain */
        $thisActivityBargain = ActivityBargain::whereId($activityBargainId)->whereStatus(1)->first();
        if($thisActivityBargain){
            /** @var Goods $goodsDetails */
            $goodsDetails = Goods::whereId($thisActivityBargain->goods_id)->whereIsShop(1)->first();
            if($goodsDetails){
                $goodsDetails->thumb_url = FileManager::getImgUrl($goodsDetails->thumb_id);

                /** @var GoodsBanner $goodsBanner */
                $goodsBanners = GoodsBanner::whereGoodId($goodsDetails->id)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
                $goodsBannerUrls = array();
                if(count($goodsBanners) > 0){
                    foreach($goodsBanners as $goodsBanner){
                        $goodsBannerUrl = FileManager::getImgUrl($goodsBanner->img_id);
                        array_push($goodsBannerUrls,$goodsBannerUrl);
                    }
                }

                $goodsDetails->goods_banner = $goodsBannerUrls;

                /** @var GoodsImg $goodsImage */
                $goodsImages = GoodsImg::whereGoodId($goodsDetails->id)->get();
                $goodsImageUrls = array();
                if(count($goodsImages) > 0){
                    foreach($goodsImages as $goodsImage){
                        $goodsImageUrl = FileManager::getImgUrl($goodsImage->thumb_id);
                        array_push($goodsImageUrls,$goodsImageUrl);
                    }
                }

                /** @var GoodSpu $goodSpu */
                $goodSpuList = GoodSpu::whereGoodsId($goodsDetails->id)->whereStatus(1)->orderBy('sort','asc')->get();

                if($goodsDetails->type == 'group'){
                    if(count($goodSpuList) > 0){
                        foreach($goodSpuList as $goodSpu){
                            /** @var ActivityGroupPrice $activityGroup */
                            $activityGroup = ActivityGroupPrice::whereActivityGroupId($activityGroupId)->whereGoodsId($goodsDetails->id)->whereGoodsSpuId($goodSpu->id)->first();
                            if($activityGroup) {
                                $goodSpu->many_price = $activityGroup->many_price;
                            }else{
                                $goodSpu->many_price = $goodSpu->price;
                            }
                        }
                    }
                }

                $goodsDetails->detailed_description      = $goodsImageUrls;
                $goodsDetails->goods_spu_info            = $goodSpuList;
                $thisActivityBargain->goods_info = $goodsDetails;
            }else{
                $thisActivityBargain->goods_info = null;
            }

        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisActivityBargain]);
    }

    /**
     * 发起砍价
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function initiateBargain(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityBargainId = !is_null($request->get('activity_bargain_id')) ? $request->get('activity_bargain_id') : 0;
        $goodsId           = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $GoodsSpuId        = !is_null($request->get('goods_spu_id')) ? $request->get('goods_spu_id') : 0;

        /** @var ActivityBargain $thisActivityBargain */
        $thisActivityBargain = ActivityBargain::whereId($activityBargainId)->whereGoodsId($goodsId)->whereStatus(1)->first();
        if(!$thisActivityBargain)
            return response()->json(['level' => 'error','message' => '该活动已下架']);

        /** @var Goods $thisGoods */
        $thisGoods = Goods::whereId($goodsId)->whereIsShop(1)->first();
        if(!$thisGoods)
            return response()->json(['level' => 'error','message' => '商品已下架']);

        /** @var GoodSpu $thisGoodsSpu */
        $thisGoodsSpu = GoodSpu::whereGoodsId($thisGoods->id)->whereId($GoodsSpuId)->whereStatus(1)->first();
        if(!$thisGoodsSpu)
            return response()->json(['level' => 'error','message' => '该属性的商品已下架']);

        if(strtotime($thisActivityBargain->start_time) > time())
            return response()->json(['level' => 'error','message' => '活动还未开始，请耐心等待']);

        if(strtotime($thisActivityBargain->end_time) <= time())
            return response()->json(['level' => 'error','message' => '该活动已过期']);

        $newInitiateBargain = new ActivityBargainInitiate();
        $newInitiateBargain->user_id                 = $user->id;
        $newInitiateBargain->ab_id                   = $thisActivityBargain->id;
        $newInitiateBargain->goods_id                = $goodsId;
        $newInitiateBargain->goods_spu_id            = $GoodsSpuId;
        $newInitiateBargain->finally_money           = $thisGoodsSpu->price;
        $newInitiateBargain->lowest_price            = (float)$thisGoodsSpu->price - (float)$thisActivityBargain->max_money;
        $newInitiateBargain->end_time                = $thisActivityBargain->end_time;
        $newInitiateBargain->save();

        return response()->json(['level' => 'success','message' => '发起成功','data' => $newInitiateBargain]);
    }

    /**
     * 获取用户发起的砍价列表
     * @param Request $request\
     */
    public function getUserInitiateBargain(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $type  = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'all';
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 0;

        /** @var ActivityBargainInitiate $activityBargainInitiate */
        if($type == 'all'){
            $activityBargainInitiates = ActivityBargainInitiate::whereUserId($user->id)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }elseif($type == 'processing'){
            $activityBargainInitiates = ActivityBargainInitiate::whereUserId($user->id)->whereStatus(0)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }elseif($type == 'over'){
            $activityBargainInitiates = ActivityBargainInitiate::whereUserId($user->id)->where('end_time','<=',date("Y-m-d H:i:s",time()))->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }else{
            $activityBargainInitiates = ActivityBargainInitiate::whereUserId($user->id)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }
        if(count($activityBargainInitiates) > 0){
            foreach($activityBargainInitiates as $activityBargainInitiate){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereType('bargain')->whereId($activityBargainInitiate->goods_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);

                    $activityBargainInitiate->goods_info = $thisGoods;
                }else{
                    $activityBargainInitiate->goods_info = null;
                }

                if($activityBargainInitiate->status == -1){
                    $activityBargainInitiate->status_name = '取消拼团';
                }elseif($activityBargainInitiate->status == 0){
                    $activityBargainInitiate->status_name = '进行中';
                }elseif($activityBargainInitiate->status == 1){
                    $activityBargainInitiate->status_name = '已完成';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityBargainInitiates]);
    }

    /**
     * 获取用户发起的砍价详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInitiateBargainDetail(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $abiId = !is_null($request->get('abi_id')) ? $request->get('abi_id') : 0;

        /** @var ActivityBargainInitiate $activityBargainInitiate */
        $activityBargainInitiate = ActivityBargainInitiate::whereId($abiId)->first();
        if($activityBargainInitiate){
            /** @var UserInfo $userInfo */
            $userInfo = UserInfo::whereUserId($activityBargainInitiate->user_id)->first();
            if($userInfo){
                $userInfo->photo_url = FileManager::getImgUrl($userInfo->photo_id);
            }

            $activityBargainInitiate->user_info = $userInfo;

            /** @var Goods $thisGoods */
            $thisGoods = Goods::whereType('bargain')->whereIsShop(1)->whereId($activityBargainInitiate->goods_id)->first();
            if($thisGoods){
                /** @var GoodsBanner $goodsBanner */
                $goodsBanners = GoodsBanner::whereGoodId($thisGoods->id)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
                $goodsBannerUrls = array();
                if(count($goodsBanners) > 0){
                    foreach($goodsBanners as $goodsBanner){
                        $goodsBannerUrl = FileManager::getImgUrl($goodsBanner->img_id);
                        array_push($goodsBannerUrls,$goodsBannerUrl);
                    }
                }

                $thisGoods->goods_banner = $goodsBannerUrls;

                /** @var GoodsImg $goodsImage */
                $goodsImages = GoodsImg::whereGoodId($thisGoods->id)->get();
                $goodsImageUrls = array();
                if(count($goodsImages) > 0){
                    foreach($goodsImages as $goodsImage){
                        $goodsImageUrl = FileManager::getImgUrl($goodsImage->thumb_id);
                        array_push($goodsImageUrls,$goodsImageUrl);
                    }
                }

                $goodSpu = GoodSpu::whereGoodsId($thisGoods->id)->whereStatus(1)->orderBy('sort','asc')->first();

                $thisGoods->detailed_description      = $goodsImageUrls;
                $thisGoods->goods_spu_info            = $goodSpu;

                $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
            }

            $activityBargainInitiate->goods_info = $thisGoods;

            /** @var ActivityBargainJoin $activityBargainJoin */
            $activityBargainJoinList = ActivityBargainJoin::whereAbiId($activityBargainInitiate->id)->get();
            if(count($activityBargainJoinList) > 0){
                foreach($activityBargainJoinList as $activityBargainJoin){
                    /** @var UserInfo $thisUserInfo */
                    $thisUserInfo = UserInfo::whereUserId($activityBargainJoin->user_id)->first();
                    if($thisUserInfo){
                        $activityBargainJoin->nickname     = $thisUserInfo->nickname;
                        $activityBargainJoin->photo_url    = FileManager::getImgUrl($thisUserInfo->photo_id);
                    }else{
                        $activityBargainJoin->nickname     = null;
                        $activityBargainJoin->photo_url    = null;
                    }
                }
            }

            $activityBargainInitiate->bargain_join_list = $activityBargainJoinList;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityBargainInitiate]);
    }

    /**
     * 砍价接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function friendBargain(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $abiId = $request->get('abi_id');

        /** @var ActivityBargainInitiate $thisActivityBargainInitiate */
        $thisActivityBargainInitiate = ActivityBargainInitiate::whereId($abiId)->first();
        if(!$thisActivityBargainInitiate)
            return response()->json(['level' => 'error','message' => '砍价活动不存在']);

        if(strtotime($thisActivityBargainInitiate->end_time) <= time())
            return response()->json(['level' => 'error','message' => '该活动已结束']);

        /** @var ActivityBargain $thisActivityBargain */
        $thisActivityBargain = ActivityBargain::whereId($thisActivityBargainInitiate->ab_id)->whereStatus(1)->first();
        if(!$thisActivityBargain)
            return response()->json(['level' => 'error','message' => '该砍价活动已下架']);

        if($thisActivityBargainInitiate->bargain_num >= $thisActivityBargain->max_join_count)
            return response()->json(['level' => 'error','message' => '该砍价活动名额已满']);

        if($thisActivityBargainInitiate->bargain_money >= $thisActivityBargain->max_money)
            return response()->json(['level' => 'error','message' => '已达到最低价，不能再砍了']);

        $isActivityBargainJoin = ActivityBargainJoin::whereUserId($user->id)->whereAbiId($thisActivityBargainInitiate->id)->first();
        if($isActivityBargainJoin)
            return response()->json(['level' => 'error','message' => '您已经砍过一刀了']);

        //本次砍价金额
        $cutPrice = 0.1;
        //剩余砍价金额
        $lastBargainMoney = (float)$thisActivityBargain->max_money - (float)$thisActivityBargainInitiate->bargain_money;
        //剩余砍价人数
        $lastBargainNum = (int)$thisActivityBargain->max_join_count - (int)$thisActivityBargainInitiate->bargain_num;
            if($thisActivityBargainInitiate->bargain_num < 10){
            $thePrice = round($thisActivityBargain->max_money * 0.25,2);
            $lastThePrice = (float)$thePrice - (float)$thisActivityBargainInitiate->bargain_money;
//            $cutAllPrice = round($thatActivityBargainJoin->last_price * 0.1,2);
            $cutAllNum   = 10 - (int)$thisActivityBargainInitiate->bargain_num;
            $cutPrice = ToolsManager::getRandomMoney($lastThePrice,$cutAllNum);
        }else{
            $cutPrice = ToolsManager::getRandomMoney($lastBargainMoney,$lastBargainNum);
        }

        //判断单次的砍价金额是否小于或等于剩余的砍价金额
        if((float)$cutPrice <= (float)$lastBargainMoney){
            $newActivityBargainJoin = new ActivityBargainJoin();
            $newActivityBargainJoin->user_id                 = $user->id;
            $newActivityBargainJoin->abi_id                  = $thisActivityBargainInitiate->id;
            $newActivityBargainJoin->bargain_money           = $cutPrice;
            $newActivityBargainJoin->participate_time        = date('Y-m-d H:i:s',time());
            $newActivityBargainJoin->save();

            $thisActivityBargainInitiate->bargain_money         = (float)$thisActivityBargainInitiate->bargain_money + (float)$cutPrice;
            $thisActivityBargainInitiate->bargain_num           = (int)$thisActivityBargainInitiate->bargain_num + 1;
            $thisActivityBargainInitiate->finally_money         = (float)$thisActivityBargainInitiate->finally_money - (float)$cutPrice;
            $thisActivityBargainInitiate->save();
        }else{
            $newActivityBargainJoin = new ActivityBargainJoin();
            $newActivityBargainJoin->user_id                 = $user->id;
            $newActivityBargainJoin->abi_id                  = $thisActivityBargainInitiate->id;
            $newActivityBargainJoin->bargain_money           = $lastBargainMoney;
            $newActivityBargainJoin->participate_time        = date('Y-m-d H:i:s',time());
            $newActivityBargainJoin->save();

            $thisActivityBargainInitiate->bargain_money         = (float)$thisActivityBargainInitiate->bargain_money + (float)$lastBargainMoney;
            $thisActivityBargainInitiate->bargain_num           = (int)$thisActivityBargainInitiate->bargain_num + 1;
            $thisActivityBargainInitiate->finally_money         = (float)$thisActivityBargainInitiate->finally_money - (float)$lastBargainMoney;
            $thisActivityBargainInitiate->save();
        }

        return response()->json(['level' => 'success','message' => '砍价成功','data' => $newActivityBargainJoin]);
    }

    /**
     * 获取拼团活动列表接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivityGroupList(Request $request){

        /** @var ActivityGroup $activityGroup */
        $activityGroupList = ActivityGroup::whereStatus(1)->where('end_time','>',date("Y-m-d H:i:s",time()))->orderBy('created_at','desc')->get();
        if(count($activityGroupList) > 0){
            foreach($activityGroupList as $activityGroup){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereType('group')->whereIsShop(1)->whereId($activityGroup->goods_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);

                    /** @var GoodSpu $goodsSpu */
                    $goodsSpu = GoodSpu::whereGoodsId($activityGroup->goods_id)->orderBy('sort','asc')->first();
                    if($goodsSpu){
                        /** @var ActivityGroupPrice $activityGroupPrice */
                        $activityGroupPrice = ActivityGroupPrice::whereGoodsId($activityGroup->goods_id)->whereGoodsSpuId($goodsSpu->id)->first();
                        if($activityGroupPrice){
                            $thisGoods->s_price   = $activityGroupPrice->many_price;
                        }else{
                            $thisGoods->s_price   = $goodsSpu->price;
                        }
                    }

                    $activityGroup->goods_info = $thisGoods;
                }else{
                    $activityGroup->goods_info = null;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityGroupList]);
    }

    /**
     * 获取活动详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivityGroupDetail(Request $request){
        $activityGroupId = !is_null($request->get('activity_group_id')) ? $request->get('activity_group_id') : 0;

        /** @var ActivityGroup $thisActivityGroup */
        $thisActivityGroup = ActivityGroup::whereId($activityGroupId)->whereStatus(1)->first();
        if(!$thisActivityGroup)
            return response()->json(['level' => 'error','message' => '该活动已下架']);

        /** @var Goods $goodsDetails */
        $goodsDetails = Goods::whereId($thisActivityGroup->goods_id)->whereType('group')->whereIsShop(1)->first();
        if($goodsDetails){
            $goodsDetails->thumb_url = FileManager::getImgUrl($goodsDetails->thumb_id);

            /** @var GoodsBanner $goodsBanner */
            $goodsBanners = GoodsBanner::whereGoodId($goodsDetails->id)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
            $goodsBannerUrls = array();
            if(count($goodsBanners) > 0){
                foreach($goodsBanners as $goodsBanner){
                    $goodsBannerUrl = FileManager::getImgUrl($goodsBanner->img_id);
                    array_push($goodsBannerUrls,$goodsBannerUrl);
                }
            }

            $goodsDetails->goods_banner = $goodsBannerUrls;

            /** @var GoodsImg $goodsImage */
            $goodsImages = GoodsImg::whereGoodId($goodsDetails->id)->get();
            $goodsImageUrls = array();
            if(count($goodsImages) > 0){
                foreach($goodsImages as $goodsImage){
                    $goodsImageUrl = FileManager::getImgUrl($goodsImage->thumb_id);
                    array_push($goodsImageUrls,$goodsImageUrl);
                }
            }

            /** @var GoodSpu $goodSpu */
            $goodSpuList = GoodSpu::whereGoodsId($goodsDetails->id)->whereStatus(1)->orderBy('sort','asc')->get();
            $groupArr = array();
            if(count($goodSpuList) > 0){
                foreach($goodSpuList as $goodSpu){
                    /** @var ActivityGroupPrice $activityGroup */
                    $activityGroup = ActivityGroupPrice::whereActivityGroupId($activityGroupId)->whereGoodsId($goodsDetails->id)->whereGoodsSpuId($goodSpu->id)->first();
                    if($activityGroup) {
                        $goodSpu->many_price = $activityGroup->many_price;
                        array_push($groupArr,$activityGroup->many_price);
                    }else{
                        $goodSpu->many_price = $goodSpu->price;
                        array_push($groupArr,$goodSpu->price);
                    }
                }
            }

            $goodSpuPrice = GoodSpu::whereGoodsId($goodsDetails->id)->whereStatus(1)->pluck('price');
            //单独购买最低价
            $goodsDetails->alone_price = min($goodSpuPrice->toArray());
            //团购最低价
            $goodsDetails->group_price = min($groupArr);

            $goodsDetails->detailed_description      = $goodsImageUrls;
            $goodsDetails->goods_spu_info            = $goodSpuList;
            $thisActivityGroup->goods_info            = $goodsDetails;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisActivityGroup]);
    }

    /**
     * 获取正在进行拼单的列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInitiateGroupList(Request $request){
        $activityGroupId = !is_null($request->get('activity_group_id')) ? $request->get('activity_group_id') : 0;

        /** @var ActivityGroup $thisActivityGroup */
        $thisActivityGroup = ActivityGroup::whereId($activityGroupId)->whereStatus(1)->first();
        if(!$thisActivityGroup)
            return response()->json(['level' => 'error','message' => '活动已下架']);

        if(strtotime($thisActivityGroup->end_time) <= time())
            return response()->json(['level' => 'error','message' => '该活动已过期']);

        /** @var ActivityGroupAdd $activityGroupOwner */
        $activityGroupOwnerList = ActivityGroupAdd::whereAgId($thisActivityGroup->id)->whereGroupId(0)->where('end_time','>',date('Y-m-d H:i:s',time()))->whereStatus(0)->get();
        if(count($activityGroupOwnerList) > 0){
            foreach($activityGroupOwnerList as $activityGroupOwner){
                /** @var UserInfo $ownerUserInfo */
                $ownerUserInfo = UserInfo::whereId($activityGroupOwner->user_id)->first();
                if($ownerUserInfo){
                    $activityGroupOwner->nickname  = $ownerUserInfo->nickname;
                    $activityGroupOwner->photo_url = FileManager::getImgUrl($ownerUserInfo->photo_id);
                }else{
                    $activityGroupOwner->nickname  = null;
                    $activityGroupOwner->photo_url = null;
                }

                /** @var ActivityGroupAdd $activityGroupAdd */
                $activityGroupAddList = ActivityGroupAdd::whereGroupId($activityGroupOwner->id)->whereStatus(0)->get();
                if(count($activityGroupAddList) > 0){
                    foreach($activityGroupAddList as $activityGroupAdd){
                        /** @var UserInfo $addUserInfo */
                        $addUserInfo = UserInfo::whereId($activityGroupAdd->user_id)->first();
                        if($addUserInfo){
                            $activityGroupAdd->nickname  = $addUserInfo->nickname;
                            $activityGroupAdd->photo_url = FileManager::getImgUrl($addUserInfo->photo_id);
                        }else{
                            $activityGroupAdd->nickname  = null;
                            $activityGroupAdd->photo_url = null;
                        }
                    }
                }

                $activityGroupOwner->group_last_num = $thisActivityGroup->max_group_num - $activityGroupOwner->group_num;
                $activityGroupOwner->group_add_list = $activityGroupAddList;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityGroupOwnerList]);
    }

    /**
     * 获取拼团团员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPayGroupAdd(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderNum = $request->get('order_num');  //团主的订单号

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereOrderNum($orderNum)->whereType('group')->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        /** @var OrderItem $thisOrderItem */
        $thisOrderItem = OrderItem::whereOrderId($thisOrder->id)->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        $result = array();
        /** @var GoodsSnapshot $thisGoodsSnapshot */
        $thisGoodsSnapshot = GoodsSnapshot::whereId($thisOrderItem->goods_snapshot_id)->first();
        if($thisGoodsSnapshot){
            $result['group_goods_name'] = $thisGoodsSnapshot->name;
            $result['group_goods_spu_name'] = $thisGoodsSnapshot->goods_spu_name;
        }else{
            $result['group_goods_name'] = null;
            $result['group_goods_spu_name'] = null;
        }



        /** @var ActivityGroup $thisActivityGroup */
        $thisActivityGroup = ActivityGroup::whereId($thisOrder->activity_id)->whereStatus(1)->first();
        if($thisActivityGroup){
            /** @var Goods $goodsDetails */
            $goodsDetails = Goods::whereId($thisActivityGroup->goods_id)->whereType('group')->whereIsShop(1)->first();
            if($goodsDetails){
                $goodsDetails->thumb_url = FileManager::getImgUrl($goodsDetails->thumb_id);

                /** @var GoodSpu $goodSpu */
                $goodSpuList = GoodSpu::whereGoodsId($goodsDetails->id)->whereStatus(1)->orderBy('sort','asc')->get();
                $groupArr = array();
                if(count($goodSpuList) > 0){
                    foreach($goodSpuList as $goodSpu){
                        /** @var ActivityGroupPrice $activityGroup */
                        $activityGroup = ActivityGroupPrice::whereActivityGroupId($thisActivityGroup->id)->whereGoodsId($goodsDetails->id)->whereGoodsSpuId($goodSpu->id)->first();
                        if($activityGroup) {
                            $goodSpu->many_price = $activityGroup->many_price;
                            array_push($groupArr,$activityGroup->many_price);
                        }else{
                            $goodSpu->many_price = $goodSpu->price;
                            array_push($groupArr,$goodSpu->price);
                        }
                    }
                }

                $goodSpuPrice = GoodSpu::whereGoodsId($goodsDetails->id)->whereStatus(1)->pluck('price');
                //单独购买最低价
                $goodsDetails->alone_price = min($goodSpuPrice->toArray());
                //团购最低价
                $goodsDetails->group_price = min($groupArr);

                $goodsDetails->goods_spu_info            = $goodSpuList;
                $thisActivityGroup->goods_info            = $goodsDetails;
                $result['activity_info'] = $thisActivityGroup;
            }else{
                $thisActivityGroup->goods_info            = null;
                $result['activity_info']                  = null;
            }
        }else{
            $result['activity_info']                  = null;
        }

        if($thisOrder->group_type == 3){
            /** @var ActivityGroupAdd $Group */
            $Group = ActivityGroupAdd::whereId($thisOrder->group_id)->first();
            if($Group){
                $thisOrder = Orders::whereOrderNum($Group->order_num)->whereType('group')->first();
                if(!$thisOrder)
                    return response()->json(['level' => 'error','message' => '团主订单号不存在']);
            }else{
                return response()->json(['level' => 'error','message' => '团主信息不存在']);
            }
        }

        /** @var ActivityGroupAdd $activityGroupAdd */
        $activityGroupAdd = ActivityGroupAdd::whereAgId($thisOrder->activity_id)->whereGroupId(0)->whereOrderNum($thisOrder->order_num)->first();
        if($activityGroupAdd){
            /** @var UserInfo $thisUserInfo */
            $thisUserInfo = UserInfo::whereUserId($activityGroupAdd->user_id)->first();
            if($thisUserInfo){
                $activityGroupAdd->nickname  = $thisUserInfo->nickname;
                $activityGroupAdd->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
            }else{
                $activityGroupAdd->nickname  = null;
                $activityGroupAdd->photo_url = null;
            }

            /** @var ActivityGroupAdd $activityGroup */
            $activityGroupChild = ActivityGroupAdd::whereGroupId($activityGroupAdd->id)->get();
            if(count($activityGroupChild) > 0){
                foreach($activityGroupChild as $activityGroup){
                    /** @var UserInfo $thisUserInfo */
                    $thisUserInfo = UserInfo::whereUserId($activityGroup->user_id)->first();
                    if($thisUserInfo){
                        $activityGroup->nickname  = $thisUserInfo->nickname;
                        $activityGroup->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                    }else{
                        $activityGroup->nickname  = null;
                        $activityGroup->photo_url = null;
                    }
                }
            }

            $activityGroupAdd->group_add_list = $activityGroupChild;
            $isActivityChild = ActivityGroupAdd::whereGroupId($activityGroupAdd->id)->whereUserId($user->id)->first();
            if($isActivityChild || ($activityGroupAdd->user_id == $user->id)){
                $result['is_join'] = true;
            }else{
                $result['is_join'] = false;
            }
            $result['group_info'] = $activityGroupAdd;
        }else{
            $result['group_info'] = null;
        }

        if($thisActivityGroup && $activityGroupAdd){
            $result['group_last_num'] = (int)$thisActivityGroup->max_group_num - (int)$activityGroupAdd->group_num;
        }else{
            $result['group_last_num'] = null;
        }

        /** @var UserInfo $thisUserInfo */
        $thisUserInfo = UserInfo::whereUserId($user->id)->first();
        if($thisUserInfo){
            $thisUserInfo->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
            $result['user_info'] = $thisUserInfo;
        }else{
            $result['user_info'] = null;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $result]);
    }

    /**
     * 获取分享二维码图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\WechatException
     */
    public function generateShareQrCode(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $groupId = !is_null($request->get('group_id')) ? $request->get('group_id') : 0;

        /** @var UserInfo $userInfo */
        $userInfo = UserInfo::whereUserId($user->id)->first();
        if(!$userInfo)
            return response()->json(['level' => 'error','message' => '用户信息不存在']);

        /** @var ActivityGroupAdd $thisActivityGroupAdd */
        $thisActivityGroupAdd = ActivityGroupAdd::whereId($groupId)->whereGroupId(0)->whereStatus(0)->first();
        if(!$thisActivityGroupAdd)
            return response()->json(['level' => 'error','message' => '拼团已结束']);

        /** @var ActivityGroup $thisActivityGroup */
        $thisActivityGroup = ActivityGroup::whereId($thisActivityGroupAdd->ag_id)->whereStatus(1)->first();
        if(!$thisActivityGroup)
            return response()->json(['level' => 'error','message' => '活动已下架']);

        if(strtotime($thisActivityGroup->end_time) <= time())
            return response()->json(['level' => 'error','message' => '活动结束了']);

        /** @var Goods $thisGoods */
        $thisGoods = Goods::whereId($thisActivityGroup->goods_id)->whereType('group')->first();
        if(!$thisGoods)
            return response()->json(['level' => 'error','message' => '拼团商品信息不存在']);

        //背景图片
        $backgroundImgInfo = Image::make(url('images/hong.png'));

        //获取头像图片地址
        if($userInfo->photo_id != 0){
            /** @var Images $thisImage */
            $thisImage = Images::whereId($userInfo->photo_id)->first();
            if($thisImage){
                /** @var Files $thisFile */
                $thisFile = Files::whereId($thisImage->file_id)->first();
                if($thisFile){
                    $userPhotoImgIContent = $thisFile->getContent();
                }else{
                    $userPhotoImgIContent = url('images/default_img.png');
                }
            }else{
                $userPhotoImgIContent = url('images/default_img.png');
            }
        }else{
            $userPhotoImgIContent = url('images/default_img.png');
        }

        //头像图片
        $userPhotoImgInfo = Image::make($userPhotoImgIContent);

        $userPhotoImgInfo->resize(80,80);

        //创建画布
        $new= Image::canvas(80,80);

        //取头像宽的一半
        $r=$userPhotoImgInfo->width() /2;

        //获取头像的款并循环
        for($x=0;$x<$userPhotoImgInfo->width();$x++) {
            //获取头像的高并循环
            for($y=0;$y<$userPhotoImgInfo->height();$y++) {
                //获取当前像素点的颜色
                $c=$userPhotoImgInfo->pickColor($x,$y,'array');

                if(((($x-$r) * ($x-$r) + ($y-$r) * ($y-$r)) < ($r*$r))) {
                    //用像素点拼出图像
                    $new->pixel($c,$x,$y);

                }

            }

        }

        //调整头像图片在背景图片上的位置
        $backgroundImgInfo->insert($new,'top-left',20,40);

        //用户昵称
        $userNicknameInfo = mb_strimwidth($userInfo->nickname,0,30,'...','utf-8');

        //调整用户昵称在图片上的位置
        $backgroundImgInfo->text($userNicknameInfo, 110, 45, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(20);
            $font->color('#fff');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //屁话
        $CommonLanguageInfo = "就差你了，拼团拿走超值商品";

        //调整屁话在图片上的位置
        $backgroundImgInfo->text($CommonLanguageInfo, 110, 100, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(20);
            $font->color('#fff');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //商品背景图
        $goodsBackgroundImgInfo = Image::make(url('images/goods-pack.png'));

        $goodsBackgroundImgInfo->resize(580,180);

        //调整商品背景图在背景图上的位置
        $backgroundImgInfo->insert($goodsBackgroundImgInfo,'top-left',10,160);

        //获取拼团商品图片
        if($thisGoods->thumb_id != 0){
            /** @var Images $thisImage */
            $thisImage = Images::whereId($thisGoods->thumb_id)->first();
            if($thisImage){
                /** @var Files $thisFile */
                $thisFile = Files::whereId($thisImage->file_id)->first();
                if($thisFile){
                    $goodsThumbImgContent = $thisFile->getContent();
                }else{
                    $goodsThumbImgContent = url('images/default_img.png');
                }
            }else{
                $goodsThumbImgContent = url('images/default_img.png');
            }
        }else{
            $goodsThumbImgContent = url('images/default_img.png');
        }

        //拼团商品图
        $goodsThumbImgINfo = Image::make($goodsThumbImgContent);

        //吊证拼团商品图大小
        $goodsThumbImgINfo->resize(180,180);

        //吊证拼团商品图在背景图上的位置
        $backgroundImgInfo->insert($goodsThumbImgINfo,'top-left',10,160);

        //商品名称
        $goodsNameInfo = mb_strimwidth($thisGoods->name,0,20,'...','utf-8');

        //调整商品名称在图片上的位置
        $backgroundImgInfo->text('【'.$goodsNameInfo.'】', 200, 165, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(25);
            $font->color('#000000');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //获取商品拼团最低价
        /** @var GoodSpu $goodSpu */
        $goodSpuList = GoodSpu::whereGoodsId($thisGoods->id)->whereStatus(1)->orderBy('sort','asc')->get();
        $groupArr = array();
        if(count($goodSpuList) > 0){
            foreach($goodSpuList as $goodSpu){
                /** @var ActivityGroupPrice $activityGroupPrice */
                $activityGroupPrice = ActivityGroupPrice::whereActivityGroupId($thisActivityGroup->id)->whereGoodsId($thisGoods->id)->whereGoodsSpuId($goodSpu->id)->first();
                if($activityGroupPrice) {
                    array_push($groupArr,$activityGroupPrice->many_price);
                }else{
                    array_push($groupArr,$goodSpu->price);
                }
            }
        }

        //商品拼团价
        $goodsGroupPrice = min($groupArr);

        //调整商品拼团价在图片上的位置
        $backgroundImgInfo->text('￥'.$goodsGroupPrice, 200, 300, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(28);
            $font->color('#CF0000');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        $goodSpuPrice = GoodSpu::whereGoodsId($thisGoods->id)->whereStatus(1)->pluck('price');
        //单独购买最低价
        $GoodsOriginalPrice = min($goodSpuPrice->toArray());

        //调整单独购买最低价在图片上的位置
        $backgroundImgInfo->text('￥'.$GoodsOriginalPrice, 300, 305, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(18);
            $font->color('#808080');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //灰色的线
        $grayLine = '————';

        //调整单独购买最低价在图片上的位置
        $backgroundImgInfo->text($grayLine, 298, 309, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(18);
            $font->color('#808080');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //拼团标志图片
        $groupImgInfo = Image::make(url('images/group.png'))->resize(100,40);

        //调整拼团图片在背景图的位置
        $backgroundImgInfo->insert($groupImgInfo,'top-left',200,200);

        $scene = "order_num=".$thisActivityGroupAdd->order_num;
        $path  = 'pages/assembleDetail/main?'.$scene;      //梓杰给

        //生成微信小程序的二维码图片
        $wxAppQrCodeContent = WechatLogin::getWxUnlimitQrcodeByToken($path);
        if($wxAppQrCodeContent){
            //获取二维码图片
            $wxAppQrCodeImgINfo = Image::make($wxAppQrCodeContent)->resize(250,250);
            //调整二维码图片在图片上的位置
            $backgroundImgInfo->insert($wxAppQrCodeImgINfo,'top-left',175,400);

        }else{
            return response()->json(['level' => 'error','message' => '二维码生成失败,请联系客服']);
        }



        //长按识别二维码
        $activityTimeInfo = "长按识别二维码，立即参团";

        //调整长按识别二维码在图片上的位置
        $backgroundImgInfo->text($activityTimeInfo,135,710, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(28);
            $font->color('#fff');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //输出图片
        $response = response()->make($backgroundImgInfo->encode('png'));
        $response->header('Content-Type', 'image/png');

        return $response;
    }

//    /**
//     * 申请退款接口
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function quitGroup(Request $request){
//        /** @var User $user */
//        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//
//        $orderNum      = $request->get('order_num');
//        $reason        = $request->get('reason');
//        $problemDesc   = $request->get('problem_desc');
//
//        /** @var Orders $thisOrder */
//        $thisOrder = Orders::whereOrderNum($orderNum)->whereUserId($user->id)->first();
//        if(!$thisOrder)
//            return response()->json(['level' => 'error','message' => '订单不存在']);
//
//        if($thisOrder->is_pay == 0)
//            return response()->json(['level' => 'error','message' => '订单未支付']);
//
//        if(is_null($reason) || $reason == '')
//            return response()->json(['level' => 'error','message' => '请输入退款原因']);
//
//        if(is_null($problemDesc) || $problemDesc != '')
//            return response()->json(['level' => 'error','message' => '请输入问题描述']);
//
//        $ActivityGroupRefund = PaymentController::Refund($thisOrder,'退出拼团成功，退还拼团金额',$user->id);
//        if($ActivityGroupRefund){
//            return response()->json(['level' => 'success','message' => '退款申请成功','data' => $ActivityGroupRefund]);
//        }else{
//            return response()->json(['level' => 'error','message' => '退款申请失败']);
//        }
//    }

}
